import { login, logout } from '@/api/user'
import { getInfo } from '@/api/trading/index'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import router from '@/router'
import { constantRoutes, allAsyncRoutes, anyRoute } from '@/router/routes'
import cloneDeep from 'lodash/cloneDeep'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    roles: [], // 当前用户的角色列表    ['角色1', '角色2']
    buttons: [], // 当前用户的按钮权限列表  ['按钮权限值1', '按钮权限值2']
    routes: JSON.parse(localStorage.getItem('info'))||[], // 用于显示导航菜单的路由数组: 常量路由 + 异步路由
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  // 设置显示菜单的路由数组
  SET_ROUTES (state, routes) {
    state.routes = routes
  },
  // 保存权限数据
  SAVE (state, {name, avatar, roles}){
    state.name = name
    state.avatar = avatar
    state.roles = roles
  },

}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.token)
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  async getInfo({ commit }, info) {
    const result = await getInfo()
    const {permissions2} = result.info.permissions2
    const {username,password} = info
    const {user} = result.info.user
    const {userList} = result.info.userList
    // console.log(username,password,user,userList);

    //routes权限路由名字  roles用户级别
    let a = user.find(item=>item.phone==username&&item.password==password)
    let b = userList.find(item=>item.id==a.id)
    let c = permissions2.find(item=>item.id==b.id)
    const {routes,roles,avatar,name} = c.data
      // 将用户的数据保存到state中(routes除外)
      commit('SAVE', {name, avatar, roles})
      // bug: 我们代码的问题
      // ​		描述: 如果先用一个A用户登陆, 退出后用B用户登陆, 结果看到与A用户相同部分的菜单是
      // ​		原因:  我们在过滤总的异步路由数组中, 过滤掉了内部部分子路由, 另一个用户登陆看不到总的路由数组了
      // ​		解决: 深拷贝然后再进行过滤 ==> 不去改变总的异步路由数组 

      // 获取过滤后的动态路由数组
      const asyncRoutes = filterAsyncRoutes(cloneDeep(allAsyncRoutes), routes) 
      
    // 合并动态权限路由和404路由
    router.addRoutes([...asyncRoutes, anyRoute])
    localStorage.setItem('info',JSON.stringify([...constantRoutes, ...asyncRoutes]))
    // 合并动态权限路由404路由和全局路由
    commit('SET_ROUTES', [...constantRoutes, ...asyncRoutes]) 
    
    router.push('/dashboard/dashboard')
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}
function filterAsyncRoutes (allAsyncRoutes, routeNames) {
  return allAsyncRoutes.filter(route => {
    // 什么情况下要过滤掉?  route的name没有在routeNames中
    if (routeNames.indexOf(route.name)===-1)  return false

    // 如果route有子路由, 需要进一步对子路由进行过滤处理, 保留过滤后的子路由数组
    if (route.children && route.children.length>0) {
      // 进行递归过滤  
        // ==> 问题: 过滤掉了allAsyncRoutes内部的一些子路由
        // ==> 如果登陆其它用户, 只能是在当前过滤后的列表中再进行过滤, 而不是总的上
      route.children = filterAsyncRoutes(route.children, routeNames)
    }
    // 留下当前route
    return true
  })
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}

